# coding=utf-8
import random

import time

from framework.common.pt_logger import logger


class RetryableRequest(object):
    def __init__(self, rqst, retry=3, min_wandering=1, max_wandering=5, retry_check=None):
        self.rqst = rqst
        self.retry = retry
        self.min_wandering = min_wandering
        self.max_wandering = max_wandering
        self.retry_check = retry_check

    def request(self, url):
        for i in range(self.retry):
            if i > 0:
                logger.info("retry %s to request..." % i)
                wandering = random.random() * (self.max_wandering - self.min_wandering) + self.min_wandering  # wandering 5 to 50 seconds
                logger.info("wandering %s seconds..." % wandering)
                time.sleep(wandering)

            try:
                response = self.rqst.request(url)
                if self.retry_check:  # customized retry check logic  # 如果请求成功，有response，并且返回状态码为200则不用重试
                    if not self.status_code_retry_check(response) and not self.retry_check(response):
                        return response
                else:
                    if not self.status_code_retry_check(response):
                        return response
            except Exception as ex:
                logger.warning("request failed, go to retry logic...")
                logger.error(ex)

            if i >= self.retry - 1:
                logger.warning("retryableRequest failed, retry %s times..." % self.retry)
                return None

    def middleware(self, middleware):
        self.rqst.middleware_list.append(middleware)
        return self

    @staticmethod
    def status_code_retry_check(response):
        if response.status_code == 200:
            return False
        else:
            return True

